# cron: 34 11 7,10,13,16,19 * * *
# new Env("小阅阅")
import requests
import time
import random
from urllib.parse import urlparse, parse_qs

class WeChatReader:
    def __init__(self, accounts):
        """
        初始化阅读器，支持多账户
        :param accounts: 账户列表，每个账户包含cookie_bbus和user_agent
        """
        self.accounts = accounts
        self.current_account_index = 0
        self.base_url = "http://1750055134te.sportsre.cn"
        # 需要检测的特殊biz列表
        self.special_biz_list = [
            "MzkxNDU1NDEzNw==",
            "Mzk5MDc1MDQzOQ=="
        ]
        # 新增变量存储动态域名
        self.dynamic_domain = None
    
    def get_current_account(self):
        """获取当前账户信息"""
        return self.accounts[self.current_account_index]
    
    def switch_account(self):
        """切换到下一个账户"""
        self.current_account_index = (self.current_account_index + 1) % len(self.accounts)
        # 切换账户时重置动态域名
        self.dynamic_domain = None
        print(f"切换到账户 {self.current_account_index + 1}/{len(self.accounts)}")
    
    def get_headers(self):
        """获取当前账户的请求头"""
        account = self.get_current_account()
        return {
            "User-Agent": account["user_agent"],
            "X-Requested-With": "XMLHttpRequest",
            "Cookie": f"bbus={account['cookie_bbus']}",
            "Referer": "http://1750055134te.sportsre.cn/haobaobao/home?v=1750055166",
            "Origin": "http://1750055134te.sportsre.cn"
        }
    
    def get_user_id(self):
        """获取用户ID"""
        url = f"{self.base_url}/haobaobao/user"
        try:
            response = requests.get(url, headers=self.get_headers())
            if response.status_code == 200:
                data = response.json()
                if data.get("errcode") == 0:
                    user_info = data.get("data", {})
                    print("用户信息:")
                    print(f"ID: {user_info.get('userid')}")
                    print(f"注册时间: {user_info.get('adddate')}")
                    print(f"备注: {user_info.get('note')}")
                    return user_info.get("userid")
        except Exception as e:
            print(f"获取用户ID失败: {e}")
        return None
    
    def get_reading_entry(self):
        """获取阅读入口"""
        url = f"{self.base_url}/mwtmpdomain"
        try:
            response = requests.post(url, headers=self.get_headers())
            if response.status_code == 200:
                data = response.json()
                if data.get("errcode") == 0:
                    domain = data.get("data", {}).get("domain")
                    print(f"获取到阅读入口: {domain}")
                    
                    # 解析域名并存储
                    parsed_url = urlparse(domain)
                    self.dynamic_domain = parsed_url.scheme + "://" + parsed_url.netloc
                    print(f"设置动态域名为: {self.dynamic_domain}")
                    
                    # 解析SK参数
                    query_params = parse_qs(parsed_url.query)
                    sk = query_params.get('sk', [None])[0]
                    
                    if sk:
                        print(f"提取到SK参数: {sk}")
                        return sk
        except Exception as e:
            print(f"获取阅读入口失败: {e}")
        return None
    
    def get_article(self, sk):
        """获取文章链接 - 使用动态域名"""
        if not self.dynamic_domain:
            print("未获取到动态域名，无法获取文章")
            return None
            
        # 构建阅读请求URL
        timestamp = int(time.time() * 1000)
        url = f"{self.dynamic_domain}/rmemakdk"
        params = {
            "time": timestamp,
            "mysign": "168",
            "vs": "120",
            "sk": sk
        }
        
        try:
            response = requests.get(url, params=params, headers=self.get_headers())
            if response.status_code == 200:
                data = response.json()
                if data.get("errcode") == 0:
                    article_data = data.get("data", {})
                    article_url = article_data.get("link")
                    article_type = article_data.get("type")
                    print(f"获取到{article_type}类型文章: {article_url}")
                    return article_url
            else:
                print(f"获取文章失败，状态码: {response.status_code}")
                print(f"响应内容: {response.text}")
        except Exception as e:
            print(f"获取文章失败: {e}")
        return None
    
    def submit_reading(self, sk):
        """提交阅读完成状态 - 使用动态域名"""
        if not self.dynamic_domain:
            print("未获取到动态域名，无法提交阅读")
            return False
            
        url = f"{self.dynamic_domain}/jiajinbimao"
        params = {
            "time": "10",
            "psign": "593",
            "sk": sk
        }
        
        try:
            response = requests.get(url, params=params, headers=self.get_headers())
            if response.status_code == 200:
                data = response.json()
                if data.get("errcode") == 0:
                    reward_data = data.get("data", {})
                    print("阅读奖励信息:")
                    print(f"金币: {reward_data.get('gold')}")
                    print(f"今日已读: {reward_data.get('day_read')}篇")
                    print(f"今日金币: {reward_data.get('day_gold')}")
                    print(f"剩余阅读: {reward_data.get('remain_read')}篇")
                    return True
        except Exception as e:
            print(f"提交阅读失败: {e}")
        return False
    
    def simulate_reading(self, article_url):
        """模拟阅读行为"""
        if not article_url:
            print("未获取到文章链接，无法模拟阅读")
            return False
        
        try:
            # 随机阅读时间（10-15秒）
            read_time = random.randint(10, 15)
            print(f"开始模拟阅读，预计耗时{read_time}秒...")
            
            # 分阶段模拟阅读
            for i in range(read_time):
                print(f"阅读中... {i+1}/{read_time}秒", end='\r')
                time.sleep(1)
            
            print("\n阅读完成！")
            return True
        except Exception as e:
            print(f"模拟阅读失败: {e}")
            return False
    
    def extract_biz(self, article_url):
        """从文章URL中提取biz参数"""
        try:
            parsed_url = urlparse(article_url)
            query_params = parse_qs(parsed_url.query)
            biz = query_params.get('__biz', [None])[0]
            return biz
        except Exception as e:
            print(f"解析biz参数失败: {e}")
            return None
    
    def check_article(self, article_url):
        """
        检测文章是否需要特殊处理
        如果biz在特殊列表中，推送到检测接口
        """
        biz = self.extract_biz(article_url)
        if not biz:
            print("未获取到biz参数，跳过检测")
            return True
        
        print(f"检测到biz参数: {biz}")
        
        # 检查是否在特殊列表中
        if biz in self.special_biz_list:
            print("发现需要检测的特殊文章，推送至检测接口...")
            # 文档2中的检测接口
            check_url = "http://192.168.0.1:5000/zdgjc"
            payload = {"url": article_url}
            
            try:
                response = requests.post(check_url, json=payload)
                if response.status_code == 200:
                    # 解析响应内容
                    response_data = response.json()
                    if response_data.get("code") == 200:
                        print("检测接口返回成功，文章安全")
                        return True
                    else:
                        print(f"检测接口返回错误: {response_data.get('msg')}")
                        return False
                else:
                    print(f"检测接口返回状态码: {response.status_code}")
                    return False
            except Exception as e:
                print(f"检测接口请求异常: {e}")
                return False
        else:
            print("文章无需特殊检测")
            return True
    
    def run_account(self, read_count=1):
        """单个账户执行阅读任务"""
        account = self.get_current_account()
        print("="*50)
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S')} 账户 {self.current_account_index+1} 开始执行阅读任务")
        print("="*50)
        
        # 获取用户ID
        user_id = self.get_user_id()
        if not user_id:
            print("无法获取用户ID，终止任务")
            return False
        
        # 获取阅读入口
        sk = self.get_reading_entry()
        if not sk:
            print("无法获取阅读入口或SK参数，终止任务")
            return False
        
        # 执行阅读任务
        success_count = 0
        for i in range(1, read_count + 1):
            print(f"\n{'='*20} 第{i}次阅读 {'='*20}")
            
            # 获取文章链接
            article_url = self.get_article(sk)
            if not article_url:
                print("获取文章失败，跳过本次阅读")
                continue
            
            # 检测文章
            if not self.check_article(article_url):
                print("文章检测未通过，终止当前账户任务")
                return False
            
            # 模拟阅读
            if self.simulate_reading(article_url):
                print("模拟阅读成功")
                
                # 提交阅读完成状态
                if self.submit_reading(sk):
                    print("阅读结果提交成功")
                    success_count += 1
                else:
                    print("阅读结果提交失败")
            
            # 随机间隔避免频繁请求
            if i < read_count:
                interval = random.randint(5, 10)
                print(f"\n等待{interval}秒后进行下一次阅读...")
                time.sleep(interval)
        
        print("\n" + "="*50)
        print(f"账户任务完成! 成功阅读 {success_count}/{read_count} 篇文章")
        print("="*50)
        return True
    
    def run(self, read_count_per_account=1):
        """多账户执行阅读任务"""
        total_accounts = len(self.accounts)
        print(f"共有 {total_accounts} 个账户，每个账户阅读 {read_count_per_account} 篇文章")
        
        for i in range(total_accounts):
            success = self.run_account(read_count_per_account)
            
            # 如果任务失败且还有账户，切换账户
            if not success and i < total_accounts - 1:
                print("任务失败，切换账户重试...")
                self.switch_account()
            else:
                break

if __name__ == "__main__":
    # 多账户配置
    ACCOUNTS = [
        {
            "cookie_bbus": "pwVlBDc3FWMVpGZTQ5TGpremJabXZiTEFHbldOOEZSWE50NGh0VEJKZVNJdUVcL28yM1ZPeVp4OUs1VFIrZ2FOMDZURkZKbkdwR3NcL0dJTWt1MlNWbXF4Q0M5K1FQcFVaTXNmUVFzT1U5UU1VdlRaXC9xeE45T3c9PSIsIm1hYyI6ImRmZDJiNzJmMmRjZTYyZTY0NzIyNWNjNjljNTBkNmU5ZWIxOGUxNDJiYmY1NzU5NDczMjE4ZjIzMTljOTZkY2UifQ%253D%253",
            "user_agent": "Mozilla/5.0 (/134.0.6998.136 Mobile Safari/537.36 XWEB/1340123 MMWEBSDK/20250201 MMWEBID/6937 MicroMessenger/8.0.58.2840(0x28003A52) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64"
        },
        # 可以添加更多账户...
    ]
    
    # 创建阅读器实例
    reader = WeChatReader(ACCOUNTS)
    
    # 执行阅读任务（每个账户默认阅读30次）
    reader.run(read_count_per_account=30)
